package com.example.shiro.config;

import com.example.shiro.entity.ShiroPermsInfo;
import com.example.shiro.entity.UserInfo;
import com.example.shiro.service.inter.ShiroPermsInfoService;
import com.example.shiro.service.inter.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.Arrays;
import java.util.List;

@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    @Lazy
    private UserInfoService userInfoService;

    @Autowired
    @Lazy
    private ShiroPermsInfoService shiroPermsInfoService;

    /**
     * 执行授权逻辑
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权逻辑");
        //设置授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        UserInfo userInfo = (UserInfo) principalCollection.getPrimaryPrincipal();
        log.error("userInfo", userInfo);
        List<ShiroPermsInfo> shiroPermsInfos = shiroPermsInfoService.selectByUserId(userInfo.getId());
        if (shiroPermsInfos != null && shiroPermsInfos.size() > 0) {
            for (ShiroPermsInfo shiroPermsInfo : shiroPermsInfos) {
                log.info("用户拥有的权限是:{}", shiroPermsInfo.getPerms());
                info.addStringPermission(shiroPermsInfo.getPerms());
            }
        } else {
            info.addStringPermission(null);
            log.info("用户没有任何拥有的权限");
        }
        System.err.println(info.getStringPermissions());
        return info;
    }

    /**
     * 执行认证逻辑
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证逻辑");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        UserInfo userInfo = userInfoService.selectByName(token.getUsername());
        if (userInfo == null) {
            return null;
        }
        log.info("当前用户登入是:{}",userInfo);
        return new SimpleAuthenticationInfo(userInfo, userInfo.getPassword(), getName());
    }
}
